package com.wswy.wzcx.ui.dmv;

import android.Manifest.permission;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.che.common.map.LocationModel;
import com.che.libcommon.api.ApiOptionalResultObserver;
import com.che.libcommon.api.BaseResult;
import com.che.libcommon.utils.JsonKit;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.wswy.wzcx.AppContext;
import com.wswy.wzcx.R;
import com.wswy.wzcx.api.Api;
import com.wswy.wzcx.model.AreaEntity;
import com.wswy.wzcx.model.dmv.ServiceCatagory;
import com.wswy.wzcx.model.dmv.ServiceInfoModel;
import com.wswy.wzcx.module.DBCity;
import com.wswy.wzcx.module.LocManager;
import com.wswy.wzcx.ui.dmv.PopupContainer.ContentViewSupplier;
import com.wswy.wzcx.utils.StringUtils;
import io.reactivex.observers.ResourceObserver;
import java.util.List;

class PopupChooser {

  private static final String SP_KEY_LAST_CITY="dmv_last_city";

  private static final String TAG = "PopupChooser";

  private AreaEntity currArea;
  private ServiceInfoModel currServiceInfo;

  private ICarDepartmentView mView;


  OnPopupSelectedCallback popupSelectedCallback;


  PopupChooser(ICarDepartmentView mView) {
    this.mView = mView;

  }



  void firstLoad(Activity activity){
    if ( !(activity instanceof FragmentActivity)){
      return;
    }
    if(!PermissionUtils.isGranted(permission.ACCESS_COARSE_LOCATION)){
      new RxPermissions((FragmentActivity) activity).request(permission.ACCESS_COARSE_LOCATION)
          .subscribe(new ResourceObserver<Boolean>() {
            @Override
            public void onNext(Boolean aBoolean) {
              if (aBoolean) {
                LocManager.getInstance().loadLocation();

                innerFirstLoad();
              }
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
          });
    }else {

      innerFirstLoad();
    }

  }


  private void innerFirstLoad(){
    String string = SPUtils.getInstance().getString(SP_KEY_LAST_CITY);
    AreaEntity entity = null;
    if(!TextUtils.isEmpty(string)){
      entity = JsonKit.GSON.fromJson(string, AreaEntity.class);
    }
    if(entity == null){
      LocationModel currentLocation = LocManager.getInstance().getCurrentLocation();

      String cityName = "上海";

      if(currentLocation != null && !TextUtils.isEmpty(currentLocation.city)){
        cityName = currentLocation.city;
      }

      DBCity city = new DBCity(AppContext.getContext());
      entity= city.findByName(StringUtils.pureAddress(cityName));
      city.close();

      if(entity != null){
        SPUtils.getInstance().put(SP_KEY_LAST_CITY,JsonKit.GSON.toJson(entity));
      }
    }

    if(entity != null){
      currArea = entity;
      mView.onChangeCity(currArea.name);
      popupSelectedCallback.onSelected(currArea,currServiceInfo);
    }
  }


  private PopupContainer cityPopup;

  private PopupContainer servicePopup;

  //显示地址选择
  void showCity(final View anchor){

    if(cityPopup == null){
      cityPopup = new PopupContainer(new CityContentViewSupplier(
          new OnFinalSelectedCallback<AreaEntity>() {
            @Override
            public void onSelected(AreaEntity areaEntity) {

              currArea = areaEntity;
              Log.e(TAG, "onSelected --> "+areaEntity);
              mView.onChangeCity(areaEntity.name);

              cityPopup.disMissPopupWindow();

              //地址选完了选服务类型
              mView.openPopup(R.id.arrow_service);


              SPUtils.getInstance().put(SP_KEY_LAST_CITY,JsonKit.GSON.toJson(areaEntity));
            }
          }));

      cityPopup.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss() {
          if(currArea != null){
            mView.onChangeCity(currArea.name);
          }
        }
      });

      cityPopup.setMaxHeight(SizeUtils.dp2px(306));
    }

    cityPopup.show(anchor);

  }

  void showService(View anchor){
    if(servicePopup == null){

      servicePopup = new PopupContainer(new ServiceContentViewSupplier(
          new OnFinalSelectedCallback<ServiceInfoModel>() {
            @Override
            public void onSelected(ServiceInfoModel serviceInfoModel) {

              currServiceInfo = serviceInfoModel;
              mView.onChangeService(serviceInfoModel.name);

              servicePopup.disMissPopupWindow();
            }
          }));

      servicePopup.setOnDismissListener(new OnDismissListener() {
        @Override
        public void onDismiss() {
          if(currServiceInfo != null){
            mView.onChangeService(currServiceInfo.name);
          }

          //地址和服务都选完了，回调
          if(currArea != null && currServiceInfo != null && popupSelectedCallback != null){
            popupSelectedCallback.onSelected(currArea,currServiceInfo);
          }

        }
      });

      servicePopup.setMaxHeight(SizeUtils.dp2px(306));
    }

    servicePopup.show(anchor);

  }


  AreaEntity getCurrArea() {
    return currArea;
  }

  ServiceInfoModel getCurrServiceInfo() {
    return currServiceInfo;
  }

  private interface OnFinalSelectedCallback<T>{
    void onSelected(T t);
  }


  interface OnPopupSelectedCallback{
    void onSelected(AreaEntity areaEntity,ServiceInfoModel serviceInfoModel);
  }


  static class CityContentViewSupplier extends SimpleContentViewSupplier<AreaEntity>{

    CityContentViewSupplier(
        OnFinalSelectedCallback<AreaEntity> finalSelectedCallback) {
      super(finalSelectedCallback);
    }

    @Override
    protected void onInit() {
      final DBCity dbCity = new DBCity(context.getApplicationContext());

      final PopupListAdapter<AreaEntity> cityAdapter = new PopupListAdapter<AreaEntity>() {
        @Override
        protected void bindData(TextView textView, AreaEntity areaEntity) {
          textView.setText(areaEntity.name);
        }

        @Override
        protected void onItemClick(AreaEntity data, int position) {
          if(finalSelectedCallback != null){
            finalSelectedCallback.onSelected(data);
          }
        }

        @Override
        protected boolean enableChangeColor() {
          return false;
        }
      };

      rvRight.setAdapter(cityAdapter);


      final List<AreaEntity> provinces = dbCity.getProvinces();

      PopupListAdapter<AreaEntity> provinceAdapter = new PopupListAdapter<AreaEntity>() {
        @Override
        protected void bindData(TextView textView, AreaEntity areaEntity) {
          textView.setText(areaEntity.name);
        }

        @Override
        protected void onItemClick(AreaEntity data, int position) {

          cityAdapter.setNewData(dbCity.getCities(data.id));

        }
      };
      rvLeft.setAdapter(provinceAdapter);

      provinceAdapter.setNewData(provinces);
    }

  }


  static class ServiceContentViewSupplier extends SimpleContentViewSupplier<ServiceInfoModel>{


    ServiceContentViewSupplier(
        OnFinalSelectedCallback<ServiceInfoModel> finalSelectedCallback) {
      super(finalSelectedCallback);
    }

    @Override
    protected void onInit() {


      final PopupListAdapter<ServiceInfoModel> serviceModelAdapter = new PopupListAdapter<ServiceInfoModel>() {
        @Override
        protected void bindData(TextView textView, ServiceInfoModel areaEntity) {
          textView.setText(areaEntity.name);
        }

        @Override
        protected void onItemClick(ServiceInfoModel data, int position) {
          if(finalSelectedCallback != null){
            finalSelectedCallback.onSelected(data);
          }
        }

        @Override
        protected boolean enableChangeColor() {
          return false;
        }
      };

      rvRight.setAdapter(serviceModelAdapter);



      final PopupListAdapter<ServiceCatagory> categoryAdapter = new PopupListAdapter<ServiceCatagory>() {
        @Override
        protected void bindData(TextView textView, ServiceCatagory areaEntity) {
          textView.setText(areaEntity.name);
        }

        @Override
        protected void onItemClick(ServiceCatagory data, int position) {

          serviceModelAdapter.setNewData(data.services);

        }
      };
      rvLeft.setAdapter(categoryAdapter);



      Api.get().getServiceCatagories().subscribe(new ApiOptionalResultObserver<List<ServiceCatagory>>() {
        @Override
        protected void onApiResult(@Nullable List<ServiceCatagory> serviceCatagories) {
          if(serviceCatagories != null){
            categoryAdapter.setNewData(serviceCatagories);
          }
        }

        @Override
        protected void onApiError(@Nullable BaseResult result) {

        }
      });


    }
  }


  static abstract class SimpleContentViewSupplier<T> implements ContentViewSupplier{

    RecyclerView rvLeft;
    RecyclerView rvRight;

    Context context;


    OnFinalSelectedCallback<T> finalSelectedCallback;

    SimpleContentViewSupplier(
        OnFinalSelectedCallback<T> finalSelectedCallback) {
      this.finalSelectedCallback = finalSelectedCallback;
    }

    @Override
    public View getView(ViewGroup container) {
      context = container.getContext();
      View inflate = LayoutInflater.from(context)
          .inflate(R.layout.layout_rv_2colums, container, false);

      rvLeft = inflate.findViewById(R.id.rv_left);
      rvRight = inflate.findViewById(R.id.rv_right);


      init();
      return inflate;
    }

    private void init(){

      rvLeft.setLayoutManager(new LinearLayoutManager(context));

      rvRight.setLayoutManager(new LinearLayoutManager(context));

      onInit();
    }

    protected abstract void onInit();

  }

}
